import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { Op } from "sequelize";
import { RESPONSE_CODE } from "@/enums/code";
import { Dict } from './dict.model'
import { CreateDictDto, UpdateDictDto, QueryDictDto, CreateDictItemDto, UpdateDictItemDto, QueryDictItemDto } from './dict.dto';
import { getPageWhere, getPageData, } from '@/utils/page'

@Injectable()
export class DictService {

  constructor(
    @InjectModel(Dict)
    private dictModel: typeof Dict,
  ) { }

  /**
   * 添加字典
   * @param createDictDto
   * @method post
   */
  async addDict(createDictDto: CreateDictDto) {
    const { dictType, description, systemFlag, remarks } = createDictDto
    const [created] = await this.dictModel.findOrCreate({
      where: {
        dictType,
      },
      defaults: {
        dictType,
        description,
        systemFlag,
        remarks,
        dictId: "",
      },
    });
    return {
      code: created ? RESPONSE_CODE.SUCCESS : RESPONSE_CODE.ERROR,
      data: null,
      msg: created ? null : '字典编码已存在'
    }
  }

  /**
   * 获取字典分页
   * @param queryDictDto
   * @method get
   */
  async getDictPage(queryDictDto: QueryDictDto) {
    const { current, size, description } = queryDictDto
    const query = { dictId: "" }
    if (description) {
      query['description'] = { [Op.like]: `${description}%` }
    }
    const { count, rows } = await this.dictModel.findAndCountAll({
      where: query,
      ...getPageWhere(current, size)
    });
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: getPageData(current, size, count, rows),
      msg: null,
    }
  }

  /**
   * 修改字典
   * @param updateDictDto
   * @method put
   */
  async updateDict(updateDictDto: UpdateDictDto) {
    const { id, description, systemFlag, remarks } = updateDictDto
    await this.dictModel.update(
      {
        description,
        systemFlag,
        remarks,
      },
      { where: { id } }
    );
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: null,
      msg: null
    }
  }

  /**
   * 获取字典详情
   * @param id
   * @method get
   */
  async getDictInfo(id: number) {
    const dict = await this.dictModel.findOne({ where: { id } });
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: dict,
      msg: null
    }
  }

  /**
   * 删除字典
   * @param id
   * @method delete
   */
  async deleteDict(id: number) {
    await this.dictModel.destroy({
      where: {
        [Op.or]: [{ id }, { dictId: id }],
      },
    });
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: [],
      msg: null
    }
  }

  /**
   * 添加字典项
   * @param createDictItemDto
   * @method post
   */
  async addDictItem(createDictItemDto: CreateDictItemDto) {
    const { dictType, dictId, label, sortOrder, value, description, remarks } = createDictItemDto
    await this.dictModel.create({
      dictId: String(dictId),
      dictType,
      label,
      sortOrder,
      value,
      description,
      remarks,
    });
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: [],
      msg: null
    }
  }

  /**
   * 修改字典项
   * @param updateDictItemDto
   * @method put
   */
  async updateDictItem(updateDictItemDto: UpdateDictItemDto) {
    const { id, dictType, dictId, label, sortOrder, value, description, remarks } = updateDictItemDto
    await this.dictModel.update({
      dictId,
      dictType,
      label,
      sortOrder,
      value,
      description,
      remarks,
    }, { where: { id } });
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: [],
      msg: null
    }
  }

  /**
   * 获取字典项分页
   * @param queryDictItemDto
   * @method get
   */
  async getDictItemPage(queryDictItemDto: QueryDictItemDto) {
    const { current, size, dictId } = queryDictItemDto
    const { count, rows } = await this.dictModel.findAndCountAll({
      where: { dictId },
      order: [["sortOrder", "ASC"]],
      ...getPageWhere(current, size)
    });

    return {
      code: RESPONSE_CODE.SUCCESS,
      data: getPageData(current, size, count, rows),
      msg: null,
    }
  }

  /**
   * 删除字典项
   * @param id
   * @method delete
   */
  async deleteDictItem(id: number) {
    await this.dictModel.destroy({
      where: { id },
    });
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: [],
      msg: null
    }
  }

  /**
   * 根据code获取字典列表
   * @param ctx
   * @method get
   */
  async getDictItemByType(dictType: string) {
    const { rows } = await this.dictModel.findAndCountAll({
      where: { dictType, dictId: { [Op.ne]: "" } },
    });
    const data = rows.map((item) => {
      return {
        ...item.dataValues,
        intValue: Number(item.dataValues.value),
      };
    });
    return {
      code: RESPONSE_CODE.SUCCESS,
      data: data,
      msg: null,
    };
  }

  /**
   * 根据code获取字典列表,不暴露接口
   * @param ctx
   */
  async getDictItem(dictType: string) {
    const { rows } = await Dict.findAndCountAll({
      where: { dictType, dictId: { [Op.ne]: "" } },
    });
    const data = rows.map((item) => {
      const { value } = item.dataValues;
      return {
        ...item.dataValues,
        intValue: isNaN(Number(value)) ? null : Number(value),
      };
    });
    return data;
  };
}
